/**
 * Appointment Management Module
 * Handles patient appointment scheduling, viewing, and management
 */
const AppointmentManager = (function() {
    // Configuration and state variables
    const config = {
        apiEndpoints: {
            getAppointments: '/api/appointments',
            createAppointment: '/api/appointments/create',
            updateAppointment: '/api/appointments/update',
            cancelAppointment: '/api/appointments/cancel',
            getDoctors: '/api/doctors/available',
            getTimeSlots: '/api/timeslots'
        },
        defaultView: 'calendar',
        appointmentStatuses: {
            PENDING: '待确认',
            CONFIRMED: '已确认',
            COMPLETED: '已完成',
            CANCELLED: '已取消',
            RESCHEDULED: '已改期'
        },
        appointmentTypes: {
            REGULAR: '常规问诊',
            FOLLOW_UP: '复诊',
            CONSULTATION: '专家会诊',
            PHYSICAL: '体检预约',
            EMERGENCY: '紧急预约'
        }
    };

    // DOM Elements cache
    let DOM = {};
    
    // Current state management
    let state = {
        appointments: [],
        doctors: [],
        selectedDate: new Date(),
        selectedDoctor: null,
        currentView: config.defaultView,
        currentTab: 'upcoming',
        isCreatingAppointment: false,
        selectedTimeSlot: null,
        selectedAppointment: null,
        calendarDate: new Date()
    };

    /**
     * Initialize the appointment module
     */
    function init() {
        cacheDOM();
        bindEvents();
        setupAppointmentPage();
        loadInitialData();
    }

    /**
     * Cache DOM elements for better performance
     */
    function cacheDOM() {
        DOM = {
            appointmentPage: document.getElementById('appointment'),
            appointmentContent: document.getElementById('appointment-content'),
            // These elements will be created dynamically
            calendar: null,
            doctorList: null,
            appointmentList: null,
            appointmentForm: null,
            tabButtons: null
        };
    }

    /**
     * Bind events to DOM elements
     */
    function bindEvents() {
        // Navigation event listeners are already handled by the main app
        // We'll add more specific event listeners after rendering the UI
    }

    /**
     * Set up the initial appointment page structure
     */
    function setupAppointmentPage() {
        // Clear the current content (placeholder message)
        DOM.appointmentPage.querySelector('.empty-page-message')?.remove();
        
        // Create and append the main structure
        const structure = createAppointmentPageStructure();
        DOM.appointmentContent = structure;
        DOM.appointmentPage.appendChild(structure);
        
        // Update cached DOM elements for the newly created elements
        updateDOMCache();
        
        // Initialize the tabs and calendar
        initializeTabs();
        renderCalendarView();
    }
    
    /**
     * Create the main structure for the appointment page
     */
    function createAppointmentPageStructure() {
        const container = document.createElement('div');
        container.className = 'appointment-container';
        container.id = 'appointment-content';
        
        container.innerHTML = `
            <div class="appointment-tabs">
                <div class="tab active" data-tab="upcoming">即将到来</div>
                <div class="tab" data-tab="history">历史记录</div>
                <div class="tab" data-tab="calendar">日历视图</div>
            </div>
            
            <div class="appointment-actions">
                <button id="create-appointment" class="btn btn-primary">
                    <i class="fas fa-plus"></i> 新预约
                </button>
            </div>
            
            <div class="tab-content active" id="upcoming-appointments">
                <div class="loading-spinner">
                    <i class="fas fa-spinner fa-spin"></i>
                    <span>加载预约...</span>
                </div>
            </div>
            
            <div class="tab-content" id="history-appointments">
                <div class="loading-spinner">
                    <i class="fas fa-spinner fa-spin"></i>
                    <span>加载历史记录...</span>
                </div>
            </div>
            
            <div class="tab-content" id="calendar-view">
                <div class="calendar-container">
                    <div class="calendar-header">
                        <button id="prev-month" class="btn-icon"><i class="fas fa-chevron-left"></i></button>
                        <h3 id="calendar-month">2023年6月</h3>
                        <button id="next-month" class="btn-icon"><i class="fas fa-chevron-right"></i></button>
                    </div>
                    <div class="calendar-weekdays">
                        <div class="weekday">日</div>
                        <div class="weekday">一</div>
                        <div class="weekday">二</div>
                        <div class="weekday">三</div>
                        <div class="weekday">四</div>
                        <div class="weekday">五</div>
                        <div class="weekday">六</div>
                    </div>
                    <div class="calendar-days" id="calendar-days"></div>
                </div>
                <div class="day-appointments" id="day-appointments">
                    <h3 id="selected-date">选择一个日期查看预约</h3>
                    <div id="selected-date-appointments"></div>
                </div>
            </div>
        `;
        
        // Create the appointment creation/details modal (hidden initially)
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'appointment-modal';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3 id="modal-title">创建预约</h3>
                    <button id="close-appointment-modal" class="btn-icon">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body" id="appointment-modal-body">
                    <!-- Content will be dynamically rendered based on context -->
                </div>
            </div>
        `;
        
        container.appendChild(modal);
        return container;
    }

    /**
     * Update the cached DOM elements after creating the structure
     */
    function updateDOMCache() {
        // Update the DOM cache with newly created elements
        DOM.tabs = document.querySelectorAll('.appointment-tabs .tab');
        DOM.tabContents = document.querySelectorAll('.tab-content');
        DOM.createAppointmentBtn = document.getElementById('create-appointment');
        DOM.calendarDays = document.getElementById('calendar-days');
        DOM.calendarMonth = document.getElementById('calendar-month');
        DOM.prevMonthBtn = document.getElementById('prev-month');
        DOM.nextMonthBtn = document.getElementById('next-month');
        DOM.selectedDate = document.getElementById('selected-date');
        DOM.selectedDateAppointments = document.getElementById('selected-date-appointments');
        DOM.upcomingAppointments = document.getElementById('upcoming-appointments');
        DOM.historyAppointments = document.getElementById('history-appointments');
        DOM.appointmentModal = document.getElementById('appointment-modal');
        DOM.modalTitle = document.getElementById('modal-title');
        DOM.modalBody = document.getElementById('appointment-modal-body');
        DOM.closeModalBtn = document.getElementById('close-appointment-modal');
        
        // Bind events now that we have the elements
        bindAppointmentEvents();
    }
    
    /**
     * Bind events specific to the appointment module
     */
    function bindAppointmentEvents() {
        // Tab switching
        DOM.tabs.forEach(tab => {
            tab.addEventListener('click', () => switchTab(tab.dataset.tab));
        });
        
        // Calendar navigation
        DOM.prevMonthBtn.addEventListener('click', () => navigateMonth(-1));
        DOM.nextMonthBtn.addEventListener('click', () => navigateMonth(1));
        
        // Create appointment button
        DOM.createAppointmentBtn.addEventListener('click', showCreateAppointmentModal);
        
        // Modal close button
        DOM.closeModalBtn.addEventListener('click', hideModal);
    }
    
    /**
     * Initialize tab functionality
     */
    function initializeTabs() {
        // Set the default active tab
        switchTab('upcoming');
    }
    
    /**
     * Switch between tabs
     */
    function switchTab(tabName) {
        state.currentTab = tabName;
        
        // Update tab buttons
        DOM.tabs.forEach(tab => {
            if (tab.dataset.tab === tabName) {
                tab.classList.add('active');
            } else {
                tab.classList.remove('active');
            }
        });
        
        // Update tab content visibility
        DOM.tabContents.forEach(content => {
            content.classList.remove('active');
        });
        
        const activeContent = document.getElementById(`${tabName}-appointments`) || 
                             document.getElementById(`${tabName}-view`);
        if (activeContent) {
            activeContent.classList.add('active');
        }
        
        // Load data specific to this tab
        if (tabName === 'upcoming') {
            loadUpcomingAppointments();
        } else if (tabName === 'history') {
            loadAppointmentHistory();
        } else if (tabName === 'calendar') {
            renderCalendarView();
        }
    }
    
    /**
     * Load the initial data required for the appointment module
     */
    function loadInitialData() {
        loadUpcomingAppointments();
        loadDoctors();
    }

    // Additional functions will be implemented in separate files
    // These will include calendar rendering, appointment CRUD operations,
    // modal handling, and API communication
    
    // Mock data for development
    function getMockAppointments() {
        return [
            {
                id: 1,
                doctorId: 101,
                doctorName: "李医生",
                doctorSpecialty: "内科",
                doctorAvatar: "/images/doctor1.jpg",
                date: "2023-07-05",
                time: "09:30",
                duration: 30,
                type: "REGULAR",
                status: "CONFIRMED",
                notes: "常规体检随访",
                location: "线上问诊"
            },
            {
                id: 2,
                doctorId: 102,
                doctorName: "王医生",
                doctorSpecialty: "心脏科",
                doctorAvatar: "/images/doctor2.jpg",
                date: "2023-07-12",
                time: "14:00",
                duration: 45,
                type: "FOLLOW_UP",
                status: "PENDING",
                notes: "心脏检查复诊",
                location: "门诊楼3楼301室"
            },
            {
                id: 3,
                doctorId: 103,
                doctorName: "张医生",
                doctorSpecialty: "神经科",
                doctorAvatar: "/images/doctor3.jpg",
                date: "2023-06-20",
                time: "10:15",
                duration: 60,
                type: "CONSULTATION",
                status: "COMPLETED",
                notes: "头痛症状咨询",
                location: "线上问诊"
            }
        ];
    }
    
    function getMockDoctors() {
        return [
            {
                id: 101,
                name: "李医生",
                specialty: "内科",
                hospital: "健康医院",
                avatar: "/images/doctor1.jpg",
                rating: 4.9,
                patientCount: 328,
                experience: "10年"
            },
            {
                id: 102,
                name: "王医生",
                specialty: "心脏科",
                hospital: "健康医院",
                avatar: "/images/doctor2.jpg",
                rating: 4.8,
                patientCount: 256,
                experience: "15年"
            },
            {
                id: 103,
                name: "张医生",
                specialty: "神经科",
                hospital: "健康医院",
                avatar: "/images/doctor3.jpg",
                rating: 4.7,
                patientCount: 198,
                experience: "8年"
            },
            {
                id: 104,
                name: "刘医生",
                specialty: "骨科",
                hospital: "健康医院",
                avatar: "/images/doctor4.jpg",
                rating: 4.6,
                patientCount: 213,
                experience: "12年"
            }
        ];
    }

    /**
     * Public API for the Appointment Manager module
     */
    return {
        init: init,
        // Additional public methods will be exposed as needed
    };
})();

// Initialize the appointment module when the DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    // We'll initialize the module when the appointment tab is clicked
    const appointmentNavItem = document.querySelector('.nav-item[data-page="appointment"]');
    if (appointmentNavItem) {
        appointmentNavItem.addEventListener('click', function() {
            // Initialize if this is the first time viewing the page
            if (!AppointmentManager.__initialized) {
                AppointmentManager.init();
                AppointmentManager.__initialized = true;
            }
        });
    }
});
